﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Reflection;

namespace Htss.Platform.Data
{
    /// <summary>
    /// 根据实体层动态实现对数据库的操作
    /// </summary>
    public class MAction<T> where T :BasicModel
    {
        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Delete(T t)
        {
            DbAction action = Create(t);
            return action.Delete();
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Update(T t)
        {
            DbAction action = Create(t);
            return action.Update();
        }
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Insert(T t)
        {
            DbAction action = Create(t);
            return action.Insert();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="t"></param>
        private DbAction Create(T t)
        {
             //实例化
            DbAction action = new DbAction();
            //获取t的具体类型
            Type type = t.GetType();
            
            //处理实体类特性
            //string tblName = String.Empty;

            object[] objTable = type.GetCustomAttributes(typeof(TableAttribute), true);

            foreach (object obj in objTable)
            {
                TableAttribute attTable = obj as TableAttribute;
                if (attTable != null)
                {
                    action.TableName = attTable.Name;
                    break;
                }
            }
           

            //处理实体类属性
            PropertyInfo[] proInfo = type.GetProperties();
            foreach (PropertyInfo pro in proInfo)
            {
                object[] objField = pro.GetCustomAttributes(typeof(FieldAttribute), true);
                if (objField.Length > 0)
                {
                    FieldAttribute field = objField[0] as FieldAttribute;

                    if (field != null)
                    {
                        //添加字段到集合中
                        object value = pro.GetValue(t, null);
                        if (value != null)
                        {
                            action.SetFields(field.Name, value, field.SqlDbType, field.Size, field.DbFieldType);
                        }
                    }
                }
            }
            return action;
        }
    }
}
